package com.example.springboot.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 第三种方式创建线程池
 */
public class ThreadPoolHelper {


    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolHelper.class);

    // 核心线程池大小
    private static final int corePoolSize = 20;
    // 最大可创建的线程数
    private static final int maxPoolSize = 200;
    // 队列最大长度
    private static final int queueCapacity = 2000;
    // 线程池维护线程所允许的空闲时间
    private static final int keepAliveSeconds = 300;

    /* 调度线程池 */
    private final ScheduledExecutorService scheduler;

    /* 业务线程池 */
    // fast/slow thread pool
    private final ThreadPoolExecutor triggerPool;

    private ThreadPoolHelper() {
        logger.info("ThreadPoolHelper init pool...");
        scheduler = new ScheduledThreadPoolExecutor(10,

                /*
                 * threadFactory可以替换成 org.apache.commons.lang3.concurrent.BasicThreadFactory,用于更精细化控制
                 * <p> new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
                 */

                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()) {
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                logger.error(t.getMessage(), t);
            }
        };

        triggerPool = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(1000),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "triggerPool-" + r.hashCode());
                    }
                });
    }


    private static class Holder {
        private static final ThreadPoolHelper INSTANCE = new ThreadPoolHelper();
    }

    public static ThreadPoolHelper getInstance() {
        return Holder.INSTANCE;
    }

    public ScheduledExecutorService getScheduler() {
        return scheduler;
    }

    public ThreadPoolExecutor getTriggerPool() {
        return triggerPool;
    }

    public void shutdown() {

        triggerPool.shutdown();

        scheduler.shutdown();

    }

}
